package presentation.concurrency;

import java.math.BigDecimal;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Account {

	private final String firstname;

	private final String lastname;

	private final BigDecimal balance;

	public Account(String firstname, String lastname, BigDecimal balance) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.balance = balance;
	}

	public String getFirstname() {
		return firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public BigDecimal getBalance() {
		return balance;
	}

	public static Builder newBuilder() {
		return new Builder();
	}

	public static class Builder {

		private String firstname;

		private String lastname;

		private BigDecimal balance;

		private ReadWriteLock rw = new ReentrantReadWriteLock();

		public String getFirstname() {
			rw.readLock().lock();
			try {
				return firstname;
			} finally {
				rw.readLock().unlock();
			}
		}

		public Builder setFirstname(String firstname) {
			rw.writeLock().lock();
			try {
				this.firstname = firstname;
				return this;
			} finally {
				rw.writeLock().unlock();
			}
		}

		public String getLastname() {
			return lastname;
		}

		public Builder setLastname(String lastname) {
			this.lastname = lastname;
			return this;
		}

		public BigDecimal getBalance() {
			return balance;
		}

		public Builder setBalance(BigDecimal balance) {
			this.balance = balance;
			return this;
		}

		public Account build() {
			return new Account(firstname, lastname, balance);
		}
	}

	public static void main(String[] args) {
		Account account = Account.newBuilder()
				.setBalance(new BigDecimal(1))
				.setFirstname("marco")
				.setLastname("villalobos")
				.build();
	}
}
